package com.bootdo.app;

import com.bootdo.common.constant.RoleConstant;
import com.bootdo.common.controller.BaseController;
import com.bootdo.common.utils.*;
import com.bootdo.system.domain.*;
import com.bootdo.system.service.*;
import com.bootdo.system.vo.CheckLogVO;
import com.bootdo.system.vo.ScoreLogVO;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/app/class/")
public class AppClassController extends BaseController {

    @Autowired
    private DeptService deptService;

    @Autowired
    private ScoreLogService scoreLogService;

    @Autowired
    private ItemService itemService;

    @Autowired
    private CheckLogService checkLogService;

    @Autowired
    private WeekService weekService;

    @Autowired
    private BeautyDeptService beautyDeptService;

    /**
     * 最美班级
     * @param params
     * @param request
     * @return
     */
    @ResponseBody
    @PostMapping("/beautyList")
    public R beautyList(@RequestParam Map<String, Object> params, HttpServletRequest request) {
        R r = checkToken(request);
        if(!StringUtils.equals(String.valueOf(r.get("code")),"0")) {
            return r;
        }
        setDateQuery(params);
        params.put("parentId","0");
        List<DeptDO> list1 = deptService.list(params);
        List<DeptDO> list2 = new ArrayList<DeptDO>();
        if(!CollectionUtils.isEmpty(list1)) {
            list1.forEach(data1 -> {
                params.put("parentId",data1.getDeptId());
                List<DeptDO> deptList = deptService.beautyList(params);
                if(!CollectionUtils.isEmpty(deptList)) {
                    data1.setChildrenList(deptList);
                    list2.add(data1);
                }
            });
        }
        return R.ok(list2);
    }

    /**
     * 获取班级得分具体记录
     * @param params
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @PostMapping("/scoreLogList")
    public R scoreLogList(@RequestParam Map<String, Object> params, HttpServletRequest request) throws Exception {
        R r = checkToken(request);
        if(!StringUtils.equals(String.valueOf(r.get("code")),"0")) {
            return r;
        }
        if(StringUtils.isEmpty((String) params.get("createdTimeStart")) && StringUtils.isEmpty((String) params.get("createdTimeEnd"))) {
            //获取当前时间属于第几周
            String strDateFormat = "yyyy-MM-dd";
            SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
            String queryDate = sdf.format(new Date());
            params.put("queryDate",queryDate);
            WeekDO weekDO = weekService.getWeekDetail(params);
            if(null != weekDO && null != weekDO.getWeekStartDate() && null != weekDO.getWeekEndDate()) {
                params.put("createdTimeStart", sdf.format(weekDO.getWeekStartDate()) + " 00:00:00");
                params.put("createdTimeEnd", sdf.format(weekDO.getWeekEndDate()) + " 23:59:59");
            }
        }
        /*UserDO userDO = (UserDO) r.get("data");*/
        /*if (userDO.getRoleIds().contains(RoleConstant.ROLE_HEAD_MASTER)) {
            params.put("deptId", userDO.getDeptId());
        }*/
        setDateQuery(params);
        //查询列表数据
        Query query = new Query(params);
        List<ScoreLogVO> scoreLogList = scoreLogService.list(query);
        int total = scoreLogService.count(query);
        PageUtils pageUtils = new PageUtils(scoreLogList,total);
        return R.ok(pageUtils);
    }

    /**
     * 得分记录详情
     * @param request
     * @param scoreLogVO
     * @return
     * @throws Exception
     */
    @ResponseBody
    @PostMapping("/getScoreLogDetail")
    public R getScoreLogDetail(HttpServletRequest request,ScoreLogVO scoreLogVO) throws Exception {
        R r = checkToken(request);
        if(!StringUtils.equals(String.valueOf(r.get("code")),"0")) {
            return r;
        }
        scoreLogVO = scoreLogService.get(scoreLogVO.getId());
        return R.ok(scoreLogVO);
    }

    /**
     * 获取班级列表
     * @param request
     * @param deptDO
     * @return
     * @throws Exception
     */
    @ResponseBody
    @PostMapping("/getClassList")
    public R getClassList(HttpServletRequest request,DeptDO deptDO) throws Exception {
        R r = checkToken(request);
        if(!StringUtils.equals(String.valueOf(r.get("code")),"0")) {
            return r;
        }
        Map<String, Object> map = new HashMap<>(16);
        map.put("parentId","0");
        List<DeptDO> deptList = deptService.list(map);
        if(!CollectionUtils.isEmpty(deptList)) {
            for(DeptDO data : deptList) {
                data.setChildrenList(getDeptChildrenList(data.getDeptId()));
            }
        }
        return R.ok(deptList);
    }

    private List<DeptDO> getDeptChildrenList(Long deptId) {
        Map<String, Object> map = new HashMap<>(16);
        map.put("parentId",deptId);
        List<DeptDO> deptList = deptService.list(map);
        if(!CollectionUtils.isEmpty(deptList)) {
            for(DeptDO data : deptList) {
                data.setChildrenList(getDeptChildrenList(data.getDeptId()));
            }
        }
        return deptList;
    }

    /**
     * 获取项目列表
     * @param request
     * @param itemDO
     * @return
     * @throws Exception
     */
    @ResponseBody
    @PostMapping("/getItemList")
    public R getItemList(HttpServletRequest request, ItemDO itemDO) throws Exception {
        R r = checkToken(request);
        if(!StringUtils.equals(String.valueOf(r.get("code")),"0")) {
            return r;
        }
        Map<String, Object> map = new HashMap<>(16);
        map.put("parentId","0");
        List<ItemDO> itemList = itemService.list(map);
        if(!CollectionUtils.isEmpty(itemList)) {
            for(ItemDO data : itemList) {
                data.setChildrenList(getItemChildrenList(data.getItemId()));
            }
        }
        return R.ok(itemList);
    }

    private List<ItemDO> getItemChildrenList(Long itemId) {
        Map<String, Object> map = new HashMap<>(16);
        map.put("parentId",itemId);
        List<ItemDO> itemList = itemService.list(map);
        if(!CollectionUtils.isEmpty(itemList)) {
            for(ItemDO data : itemList) {
                data.setChildrenList(getItemChildrenList(data.getItemId()));
            }
        }
        return itemList;
    }

    /**
     * 值日生打分评价
     * @param request
     * @param scoreLogDO
     * @return
     * @throws Exception
     */
    @ResponseBody
    @PostMapping("/saveScore")
    public R saveScore(HttpServletRequest request, ScoreLogDO scoreLogDO) throws Exception {
        R r = checkToken(request);
        if(!StringUtils.equals(String.valueOf(r.get("code")),"0")) {
            return r;
        }
        UserDO userDO = (UserDO) r.get("data");
        Date now = new Date();
        if (userDO.getRoleIds().contains(RoleConstant.ROLE_WORKER)) {
            //值日生角色(审核状态，1审核通过，0待审核，2审核不通过)
            scoreLogDO.setStatus("0");
        }else {
            //默认审核通过
            scoreLogDO.setStatus("1");
            scoreLogDO.setVerifyTime(now);
            scoreLogDO.setVerifyBy(userDO.getUserId());
            DeptDO dept = deptService.get(scoreLogDO.getDeptId());
            if(null == dept) {
                dept.setScore(scoreLogDO.getScore());
            }else {
                dept.setScore(dept.getScore()+scoreLogDO.getScore());
            }
            deptService.update(dept);
        }
        scoreLogDO.setCreatedBy(userDO.getUserId());
        scoreLogDO.setCreatedTime(now);
        scoreLogDO.setId(UuidUtils.getUUID());
        scoreLogService.save(scoreLogDO);
        return R.ok();
    }

    /**
     * 管理员编辑打分评价
     * @param request
     * @param scoreLogDO
     * @return
     * @throws Exception
     */
    @ResponseBody
    @PostMapping("/updateScore")
    public R updateScore(HttpServletRequest request, ScoreLogDO scoreLogDO) throws Exception {
        R r = checkToken(request);
        if(!StringUtils.equals(String.valueOf(r.get("code")),"0")) {
            return r;
        }
        UserDO userDO = (UserDO) r.get("data");
        //默认审核通过
        /*scoreLogDO.setStatus("1");
        scoreLogDO.setVerifyTime(new Date());
        scoreLogDO.setVerifyBy(userDO.getUserId());*/
        ScoreLogVO scoreLogVO = scoreLogService.get(scoreLogDO.getId());
        DeptDO dept = deptService.get(scoreLogDO.getDeptId());
        //修改先减去之前评价的分数在加上重新修改的分数
        dept.setScore(dept.getScore() - scoreLogVO.getScore() +scoreLogDO.getScore());
        deptService.update(dept);
        scoreLogDO.setUpdatedBy(userDO.getUserId());
        scoreLogDO.setUpdatedTime(new Date());
        scoreLogDO.setCreatedTime(null);
        scoreLogService.updateScore(scoreLogDO);
        return R.ok();
    }

    /**
     * 打分评价审核
     * @param scoreLogDO
     * @return
     */
    @ResponseBody
    @RequestMapping("/check")
    public R check(HttpServletRequest request, ScoreLogDO scoreLogDO) throws Exception {
        R r = checkToken(request);
        if(!StringUtils.equals(String.valueOf(r.get("code")),"0")) {
            return r;
        }
        UserDO userDO = (UserDO) r.get("data");
        scoreLogDO.setCreatedTime(null);
        scoreLogService.update(scoreLogDO,userDO);
        return R.ok();
    }

    /**
     * 分值统计
     * @param params
     * @return
     */
    @ResponseBody
    @RequestMapping("/countScore")
    public R countScore(HttpServletRequest request, @RequestParam Map<String, Object> params) {
        R r = checkToken(request);
        if(!StringUtils.equals(String.valueOf(r.get("code")),"0")) {
            return r;
        }
        setDateQuery(params);
        int socre = scoreLogService.getScore(params);
        //查询列表数据
        return R.ok().put("score",socre);
    }

    /**
     * 获取安全检查记录列表数据
     * @param params
     * @param request
     * @return
     */
    @ResponseBody
    @PostMapping("/safeCheckLogList")
    public R safeCheckLogList(@RequestParam Map<String, Object> params, HttpServletRequest request) {
        R r = checkToken(request);
        if(!StringUtils.equals(String.valueOf(r.get("code")),"0")) {
            return r;
        }
        UserDO userDO = (UserDO) r.get("data");
        if (userDO.getRoleIds().contains(RoleConstant.ROLE_HEAD_MASTER)) {
            params.put("deptId", userDO.getDeptId());
        }
        //查询列表数据
        Query query = new Query(params);
        List<CheckLogVO> checkLogList = checkLogService.list(query);
        int total = checkLogService.count(query);
        PageUtils pageUtils = new PageUtils(checkLogList,total);
        return R.ok(pageUtils);
    }

    /**
     * 安全检查记录审核
     * @param checkLogDO
     * @return
     */
    @ResponseBody
    @RequestMapping("/checkSafeCheckLog")
    public R checkSafeCheckLog(HttpServletRequest request, CheckLogDO checkLogDO) {
        R r = checkToken(request);
        if(!StringUtils.equals(String.valueOf(r.get("code")),"0")) {
            return r;
        }
        UserDO userDO = (UserDO) r.get("data");
        checkLogDO.setCheckUserId(userDO.getUserId());
        checkLogDO.setCheckTime(new Date());
        checkLogDO.setStatus("1");
        checkLogService.update(checkLogDO);
        return R.ok();
    }

    /**
     * 获取安全检查记录详情
     * @param request
     * @param checkLogVO
     * @return
     */
    @ResponseBody
    @PostMapping("/getSafeCheckLogDetail")
    public R getScoreLogDetail(HttpServletRequest request,CheckLogVO checkLogVO) {
        R r = checkToken(request);
        if(!StringUtils.equals(String.valueOf(r.get("code")),"0")) {
            return r;
        }
        checkLogVO = checkLogService.get(checkLogVO.getId());
        return R.ok(checkLogVO);
    }

    /**
     * 获取当前月第一天和最后一天
     * @return
     */
    @ResponseBody
    @PostMapping("/getDateDetail")
    public R getDateDetail() {
        Map<String,Object> map = new HashMap<String, Object>();
        Date firstDay = DateUtils.getFirstDay();
        Date lastDay = DateUtils.getLastDay();
        map.put("firstDay",firstDay);
        map.put("lastDay",lastDay);
        return R.ok(map);
    }

    /**
     * 获取学期，星期
     * @param weekDO
     * @return
     */
    @ResponseBody
    @PostMapping("/weekList")
    public List<WeekDO> listFor(WeekDO weekDO){
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("parentId",weekDO.getParentId().toString());
        List<WeekDO> list = weekService.list(params);
        return list;
    }

    /**
     * 获取学期美丽班级列表数据
     * @param params
     * @return
     */
    @ResponseBody
    @PostMapping("/beautyClassList")
    public R beautyClassList(@RequestParam Map<String, Object> params, HttpServletRequest request) {
        R r = checkToken(request);
        if(!StringUtils.equals(String.valueOf(r.get("code")),"0")) {
            return r;
        }
        //查询列表数据
        setDateQuery(params);
        params.put("parentId","0");
        List<DeptDO> list1 = deptService.list(params);
        List<DeptDO> list2 = new ArrayList<DeptDO>();
        if(!CollectionUtils.isEmpty(list1)) {
            list1.forEach(data1 -> {
                params.put("parentId",data1.getDeptId());
                List<DeptDO> deptList = beautyDeptService.beautyClassList(params);
                if(!CollectionUtils.isEmpty(deptList)) {
                    data1.setChildrenList(deptList);
                    list2.add(data1);
                }
            });
        }
        return R.ok(list2);
    }
}
